class Solution(object):
    def getMaximumGold(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        self.m = len(grid)
        self.n = len(grid[0])
        max_gold = 0
        for i in range(self.m):
            for j in range(self.n):
                if grid[i][j] != 0:
                    gold_collected = self.dfs(grid, i, j)
                    if gold_collected > max_gold:
                        max_gold = gold_collected
        return max_gold

    def dfs(self, grid, i, j):
        gold_here = grid[i][j]
        grid[i][j] = 0
        max_next = 0
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for dx, dy in directions:
            ni, nj = i + dx, j + dy
            if 0 <= ni < self.m and 0 <= nj < self.n and grid[ni][nj] != 0:
                next_gold = self.dfs(grid, ni, nj)
                if next_gold > max_next:
                    max_next = next_gold
        grid[i][j] = gold_here
        return gold_here + max_next